import { MODEL_NAME } from '../../constants/model-names';
import { EVENTS, type IEventBus } from '../../events';
import type {
  BattleLevelModel,
  PlayerAttributesModel,
  RealmModel,
} from '../../model';
import { RealmReader } from '../../model/realm/realm-reader';
import { BaseSystem } from '../base';
import type { PlayerStateSystem } from '../player-state';

export class PlayerAttributesSystem extends BaseSystem {
  private bus: IEventBus;
  private playerStateSystem: PlayerStateSystem;

  constructor(bus: IEventBus, playerStateSystem: PlayerStateSystem) {
    super();
    this.bus = bus;
    this.playerStateSystem = playerStateSystem;

    this.bus.on(EVENTS.BATTLE_LEVEL_UP, () => {
      const playerAttributesModel =
        this.playerStateSystem.getModel<PlayerAttributesModel>(
          MODEL_NAME.PLAYER_ATTRIBUTES
        );
      const battleLevelModel =
        this.playerStateSystem.getModel<BattleLevelModel>(
          MODEL_NAME.BATTLE_LEVEL
        );
      if (!playerAttributesModel || !battleLevelModel) return;
      playerAttributesModel.setLevel(battleLevelModel.getLevelInfo().level);
    });
  }

  public init(): void {
    const playerAttributesModel =
      this.playerStateSystem.getModel<PlayerAttributesModel>(
        MODEL_NAME.PLAYER_ATTRIBUTES
      );
    const battleLevelModel = this.playerStateSystem.getModel<BattleLevelModel>(
      MODEL_NAME.BATTLE_LEVEL
    );
    const realmModel = this.playerStateSystem.getModel<RealmModel>(
      MODEL_NAME.REALM
    );
    /** 初始化玩家属性的战斗等级 */
    playerAttributesModel.setLevel(battleLevelModel.getLevelInfo().level);

    /** 初始化玩家属性的大小境界 */
    const realmConfig = RealmReader.getRealmConfigByLevel(
      realmModel.getRealm()
    );
    playerAttributesModel.setRealm(
      realmConfig.bigLevelType,
      realmConfig.smallLevel
    );
  }
}
